import sys,os,time,sqlite3
import sys,os,time,serial,sqlite3
sys.stderr = sys.stdout
from PyQt4 import QtCore, QtGui
from telas import Ui_telas
from configdialog import Ui_config

from testador import Testador
from configuracoes import Configuracoes

from lista_comandos import Lista_Comandos
from time import sleep

from variaveisui import Variaveisui

from tabelaoem import Tabelaoem
from apptxt import AlteraApp
from variaveis import Variaveis

from threading import Timer

from kthread import KThread

from linha_comando import Linha_comando
import binascii

from cronometro import Cronometro

#by Varaska
from timestamp import Ui_Dialog_Timestamp

sys.path.append('./aaaaaa')
from main import TSFTP

class StartQt4(QtGui.QMainWindow):

    def keyPressEvent(self, event):
        if (event.key() == QtCore.Qt.Key_F1):
            self.ui.comandoSerial.selectAll()
            self.ui.comandoSerial.setFocus()

        elif (event.key() == QtCore.Qt.Key_F2):
            self.ui.comandoSSH.selectAll()
            self.ui.comandoSSH.setFocus()

        elif (event.key() == QtCore.Qt.Key_F3):
            self.fotaozin()
            #pass

        elif (event.key() == QtCore.Qt.Key_F4):           
            self.ui.useHex.setChecked(True)
            self.conversaomegapower(True)
            
        elif (event.key() == QtCore.Qt.Key_F5):
            self.ui.useDec.setChecked(True)
            self.conversaomegapower(True)
            
        elif (event.key() == QtCore.Qt.Key_F7):
            self.timestamp()
            
        elif (event.key() == QtCore.Qt.Key_F6):
            #self.fotaozin2()
            pass
        else:
            QtGui.QMainWindow.keyPressEvent(self,event)

    def closeEvent(self, closeevent):
        arquivo = open(self.PASTA+'/teste.a','wb')
        arquivo.write( self.saveState() )
        arquivo.write( '\n' )
        arquivo.write( self.ui.splitter.saveState() )
        arquivo.close()
        
        print 'sucesso!'
        # QtGui.QMainWindow.closeEvent(self, closeevent)

    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_telas()
        self.ui.setupUi(self)
        self.setWindowState(QtCore.Qt.WindowMaximized)
        self.PASTA = str(QtCore.QDir.currentPath())
        
        self.nomedobanco = 'banco.db'

        self.setWindowIcon(QtGui.QIcon('icons/Caminhao.png'))

        QtCore.QObject.connect(self.ui.f1config, QtCore.SIGNAL("clicked()"), self.telaf1config)
        QtCore.QObject.connect(self.ui.f2config, QtCore.SIGNAL("clicked()"), self.telaf2config)
        
        QtCore.QObject.connect(self.ui.limparf1, QtCore.SIGNAL("clicked()"), self.ui.tfiltro1.clear)
        QtCore.QObject.connect(self.ui.limparf2, QtCore.SIGNAL("clicked()"), self.ui.tfiltro2.clear)

        
        # timestamp
        QtCore.QObject.connect(self.ui.actionTimestampSerial, QtCore.SIGNAL("triggered()"), self.trocaTimestampSerial)
        QtCore.QObject.connect(self.ui.actionTimestampSSH, QtCore.SIGNAL("triggered()"), self.trocaTimestampSSH)
        
        # QtCore.QObject.connect(self.ui.filtros, QtCore.SIGNAL("visibilityChanged(bool)"), self.ui.actionMostrarFiltros.setChecked)
        QtCore.QObject.connect(self.ui.actionMostrarFiltros, QtCore.SIGNAL("triggered()"), self.mostrafiltros)
        
        QtCore.QObject.connect(self.ui.actionSobre, QtCore.SIGNAL("triggered()"), self.sobre)
        QtCore.QObject.connect(self.ui.actionLimparSSH, QtCore.SIGNAL("triggered()"), self.ui.tssh.clear)
        QtCore.QObject.connect(self.ui.limparSerial, QtCore.SIGNAL("triggered()"), self.ui.tserial.clear)
        QtCore.QObject.connect(self.ui.comandoSSH,QtCore.SIGNAL("returnPressed()"),self.enviarComandoSSH)
        QtCore.QObject.connect(self.ui.comandoSerial,QtCore.SIGNAL("returnPressed()"),self.enviarComandoSerial)
        QtCore.QObject.connect(self.ui.actionSair,QtCore.SIGNAL("triggered()"),self.close_window)
        QtCore.QObject.connect(self.ui.conexSSH,QtCore.SIGNAL("triggered()"),self.conexssh)
        QtCore.QObject.connect(self.ui.conexSerial,QtCore.SIGNAL("triggered()"),self.conexserial)
        QtCore.QObject.connect(self.ui.actionManual,QtCore.SIGNAL("triggered()"),self.abrirmanual)
        QtCore.QObject.connect(self.ui.actionApp,QtCore.SIGNAL("triggered()"),self.abrirappoem)
        QtCore.QObject.connect(self.ui.actionOut,QtCore.SIGNAL("triggered()"),self.abriroutoem)
        QtCore.QObject.connect(self.ui.actionAppTxt,QtCore.SIGNAL("triggered()"), self.apptxt)
        QtCore.QObject.connect(self.ui.fotaozin,QtCore.SIGNAL("triggered()"), self.fotaozin)
        QtCore.QObject.connect(self.ui.actionSCP,QtCore.SIGNAL("triggered()"), self.abrirscp)

        self.tester = Testador()
        self.setWindowTitle("Rastreador tester - "+self.tester.ultimoarquivo)
        QtCore.QObject.connect(self.tester, QtCore.SIGNAL("alteraserial(PyQt_PyObject)"), self.atualizaSerial)
        QtCore.QObject.connect(self.tester, QtCore.SIGNAL("alterassh(PyQt_PyObject)"), self.ui.tssh.inserir)
        QtCore.QObject.connect(self.tester, QtCore.SIGNAL("connectsuccess()"), self.conectsucesso)
        QtCore.QObject.connect(self.tester, QtCore.SIGNAL("connectfailed(PyQt_PyObject)"), self.conectnsucesso)

        #finds
        QtCore.QObject.connect(self.ui.bsshabaixo, QtCore.SIGNAL("clicked()"), self.findsshabaixo)
        QtCore.QObject.connect(self.ui.bsshacima, QtCore.SIGNAL("clicked()"), self.findsshacima)
        QtCore.QObject.connect(self.ui.bserialabaixo, QtCore.SIGNAL("clicked()"), self.findserialabaixo)
        QtCore.QObject.connect(self.ui.bserialacima, QtCore.SIGNAL("clicked()"), self.findserialacima)
        
        #configruacao
        QtCore.QObject.connect(self.ui.actionConfigura, QtCore.SIGNAL("triggered()"), self.configuradialog)
        QtCore.QObject.connect(self.ui.actionAbrir, QtCore.SIGNAL("triggered()"), self.abrirconfig)
        QtCore.QObject.connect(self.ui.actionSalvar, QtCore.SIGNAL("triggered()"), self.salvarconfig)
        QtCore.QObject.connect(self.ui.actionSalvarPadrao, QtCore.SIGNAL("triggered()"), self.salvarpadraoconfig)

        # Word wrap
        QtCore.QObject.connect(self.ui.actionWrapSerial, QtCore.SIGNAL("triggered()"), self.wrapserial)
        QtCore.QObject.connect(self.ui.actionWrapSSH, QtCore.SIGNAL("triggered()"), self.wrapssh)

        
        QtCore.QObject.connect(self.ui.useDec, QtCore.SIGNAL("clicked()"), self.antesdaconversaomegapower)
        QtCore.QObject.connect(self.ui.useHex, QtCore.SIGNAL("clicked()"), self.antesdaconversaomegapower)
        
        
        self.iconoff = QtGui.QIcon(":/new/prefix1/icons/conectar.png")
        self.iconon = QtGui.QIcon(":/new/prefix1/icons/desconectar.png")
        
        #GAMBI
        from printer import Printer
        self.evaluero = Printer()
        QtCore.QObject.connect(self.evaluero, QtCore.SIGNAL("reqvariavel(PyQt_PyObject)"), self.evaluar)
        self.buffer1 = ''
        self.conectarssh()
        self.conectarserial()
        
        # self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.ui.filtros)
        
        #lista de "lugares onde da pra selecionar"
        self.listaDeLugaresSelecionaveis = []
        self.listaDeLugaresSelecionaveis.append(self.ui.tserial)
        self.listaDeLugaresSelecionaveis.append(self.ui.tssh)
        self.listaDeLugaresSelecionaveis.append(self.ui.tfiltro1)
        self.listaDeLugaresSelecionaveis.append(self.ui.tfiltro2)
        self.listaDeLugaresSelecionaveis.append(self.ui.comandoSerial)
        self.listaDeLugaresSelecionaveis.append(self.ui.comandoSSH)
        self.ultimovalorselecionado = ''
        
        for item in self.listaDeLugaresSelecionaveis:
            if not isinstance(item,Linha_comando):
                QtCore.QObject.connect(item,QtCore.SIGNAL("cursorPositionChanged ()"),self.conversaomegapower)
            else:
                QtCore.QObject.connect(item, QtCore.SIGNAL("selectionChanged()"), self.conversaomegapower)
    
        try:
            arquivo = open(self.PASTA+'/teste.a','rb')
            a = arquivo.readlines(  )
            arquivo.close()
            #print a
            self.restoreState(QtCore.QByteArray (a[0][:-1]) )
            self.ui.splitter.restoreState(QtCore.QByteArray (a[1]) )
        except Exception, e:
            print e
            
        #Inicializacoes do Coronometro
        self.cronometro = Cronometro(self.ui.sbHora,self.ui.sbMin,self.ui.sbSeg,self.ui.rbProg,self.ui.rbReg,self.ui.bPlay,self.ui.bPause,self.ui.bReset)
        QtCore.QObject.connect(self.cronometro, QtCore.SIGNAL("pisca()"), self.pisca )

    # ---------------------- FIM INIT ---------------------------
    def setarapp(self, app):
        self.app = app
        
    def pisca(self):
        self.app.alert(self, 0)
        
    def wrapserial(self):
        if self.ui.tserial.lineWrapMode():
            self.ui.tserial.setLineWrapMode(0)
        else:
            self.ui.tserial.setLineWrapMode(1)

    def wrapssh(self):
        if self.ui.tssh.lineWrapMode():
            self.ui.tssh.setLineWrapMode(0)
        else:
            self.ui.tssh.setLineWrapMode(1)

    def abrirscp(self):
        if self.tester.ssh.conectado:
            telasftp = TSFTP(self.tester.ssh.transport)
            telasftp.show()
            telasftp.setVisible()
        else:
            print 'o ssh ainda nao ta conectado carai'

    def evaluar(self, texto):
        try:
            print '%s: %s' % (texto,eval(texto))
        except:
            exec(texto)
  
    
    def antesdaconversaomegapower(self):
        print 'olha eu mae'
        self.conversaomegapower(True)

    def abrirconfig(self):
        print 'abrir config'
        # fd = QtGui.QFileDialog(self)
        # fd.setAcceptMode(QtGui.QFileDialog.QAcceptOpen)
        # fd.setFileMode(QtGui.QFileDialog.
        fd = QtGui.QFileDialog(self)
        filtro = QtCore.QStringList()
        arquivo = fd.getOpenFileName(None,'Escolha um arquivo de configuracao', os.getcwd(), 'Config File (*.ini)')
        if arquivo:
            self.tester.abreConfiguracoes(arquivo)
            self.setWindowTitle("Rastreador tester - "+self.tester.ultimoarquivo)
        
    def salvarconfig(self):
        print 'salvar config'
        fd = QtGui.QFileDialog(self)
        filtro = QtCore.QStringList()
        arquivo = fd.getSaveFileName(None,'Escolha um arquivo de configuracao', os.getcwd(), 'Config File (*.ini)')
        if arquivo:
            self.salvarpadraoconfig(arquivo)
            self.tester.abreConfiguracoes(arquivo)
            self.setWindowTitle("Rastreador tester - "+self.tester.ultimoarquivo)
        
    def salvarpadraoconfig(self, arquivo = 'config.ini'):
        print 'salvar padrao config'
        print arquivo
        if self.tester.ultimoarquivo <> 'config.ini' or arquivo <> 'config.ini':
            f = open(arquivo,'w')
            original = open(self.tester.ultimoarquivo)
            f.write(original.read())
            original.close()
            f.close()
  
    def findsshabaixo(self):
        if str(self.ui.findssh.text()).strip(" ") <> "":
            self.ui.tssh.find(self.ui.findssh.text())

    def findsshacima(self):
        if str(self.ui.findssh.text()).strip(" ") <> "":
            self.ui.tssh.find(self.ui.findssh.text(),QtGui.QTextDocument.FindBackward)

    def findserialabaixo(self):
        if str(self.ui.findserial.text()).strip(' ') <> '':
            self.ui.tserial.find(self.ui.findserial.text())
            
    def findserialacima(self):
        if str(self.ui.findserial.text()).strip(' ') <> '':
            self.ui.tserial.find(self.ui.findserial.text(),QtGui.QTextDocument.FindBackward)
            
    def conexserial(self):
        if self.tester.conectadoSerial:
            self.desconectarserial()
        else:
            self.conectarserial()
    def conexssh(self):
        if self.tester.ssh.conectado:
            self.desconectarssh()
        else:
            self.conectarssh()
            
    
    def conversaomegapower(self, vimpelomouse=False):
        if vimpelomouse:
            texto = self.ultimovalorselecionado
        else:
            texto = ''
            for item in self.listaDeLugaresSelecionaveis:
                if item.hasFocus():
                    try:
                        if isinstance(item,Linha_comando):
                            texto = str(item.selectedText())
                        else:
                            texto = str(item.textCursor().selectedText())
                        self.ultimovalorselecionado = texto
                    except:
                        pass
                    break
        if len(texto) > 0:
            try:
                if self.ui.useHex.isChecked():
                    tbin = bin(int(texto,16))[2:]
                    tdec = int(texto,16)
                    thex = texto
                else:
                    tbin = bin(int(texto))[2:]
                    tdec = texto
                    thex = hex(int(texto))[2:]
                tbin = str.zfill(str(tbin),8)
            except Exception, e:
                # print "deu merda"
                # print e
                tbin = tdec = thex = '####'
            tam = len(str(thex))
            if tam%2 > 0:
                hstr = '0'+str(thex)
            else:
                hstr = str(thex)
            self.ui.tcbin.setText('b: '+tbin)
            self.ui.tcdec.setText('d: '+str(tdec))
            self.ui.tchex.setText('h: '+hstr)
        
         
        
    # gambiarra do arabori       
    def fotaozin(self):
        config = AutoConfigurator(self.tester,self)
        config.setModal(True)
        config.show()
            
    #fim da gambiarra
    
    def trocaTimestampSerial(self):
        try:
            self.tester.trocaTimestampSerial()
        except:
            QtGui.QMessageBox.critical(self,'Erro!','Tem q tar conectado a parada!')
            self.ui.actionTimestampSerial.setChecked(True)

    def trocaTimestampSSH(self):
        try:
            self.tester.trocaTimestampSSH()
        except:
            QtGui.QMessageBox.critical(self,'Erro!','Tem q tar conectado a parada!')
            self.ui.actionTimestampSSH.setChecked(True)

    def gravatelainout(self):
        pass
        # conn = sqlite3.connect(self.nomedobanco)
        # c = conn.cursor()
        # c.execute("update posicaotela SET inout_x=%s, inout_y=%s, inout_h=%s, inout_w=%s,floating=%s, visible=%s, telameio=%s, rdSend=0 where id=2"
               # % (self.ui.filtros.x(), self.ui.filtros.y(), self.ui.filtros.height(), self.ui.filtros.width(),
                   # int(self.ui.filtros.isFloating()), int(self.ui.filtros.isVisible()),0)
               # )
        # conn.commit()
        # conn.close()
            
    def mostrafiltros(self):
        if self.ui.filtros.isVisible():
            self.ui.filtros.hide()
        else:
            self.ui.filtros.show()
            
    def abretelainout(self):
        pass
        # conn = sqlite3.connect(self.nomedobanco)
        # c = conn.cursor()
        # try:
            # c.execute("CREATE TABLE posicaotela (id INTEGER, inout_x INTEGER, inout_y INTEGER, inout_h INTEGER, inout_w INTEGER, floating INTEGER, visible INTEGER, telameio INTEGER, rdSend INTEGER)")
            # conn.commit()
        # except Exception, err:
            # print err
            # pass
            
        # c = conn.cursor()
        # try:
            # c.execute("INSERT INTO posicaotela VALUES (2,0,0,0,0,0,0,1,0)")
            # conn.commit()
        # except Exception, err:
            # print err
            # pass

        # c.execute("select * from posicaotela where id=2")
        # linha = c.fetchall()
        # print linha
        # for x in linha:
            # self.ui.filtros.setFloating(bool(x[5]))
            # self.ui.filtros.setGeometry(x[1], x[2], x[4], x[3] )
            # if x[6]:
                # self.ui.filtros.show()
            # else:
                # self.ui.filtros.close()
                
        # conn.close()
                
    def apptxt(self):
        if self.tester.ssh.conectado:
            txt = AlteraApp(self, self.tester.ssh.transport)
            txt.show()
                
    def abrirappoem(self):
        self.abriroem('OEMApplication.txt')

    def abriroutoem(self):
        self.abriroem('OEMOutputs.txt')

    def abriroem(self,oem):
        if self.tester.ssh.conectado:
            tab = Tabelaoem(self,self.tester.ssh.transport,oem)
            tab.show()

    def abrirmanual(self):
        os.startfile(os.getcwd() + '/Manual/Manual.pdf')
       
    def conectsucesso(self):
        self.ui.tssh.append("OK")
        self.ui.conexSSH.setIcon(self.iconon)
        self.tester.conectarrastrear()
        self.ui.conexSSH.setToolTip("Desconectar")

    def conectnsucesso(self, msg):
        QtGui.QMessageBox.critical(self,'Erro!','Nao foi possivel estabelecer a conexao com o servidor:\n'+str(msg))

    def conectarssh(self):
        self.ui.tssh.append('\nConectando...')
        self.tester.conectarssh()
        self.ui.actionTimestampSSH.setChecked(True)

    def desconectarssh(self):
        self.ui.tssh.append('\nDesconectando...')
        self.tester.desconectarssh()
        self.ui.conexSSH.setIcon(self.iconoff)
        self.ui.conexSSH.setToolTip("Conectar")
    
    def atualizaFiltros(self, filtro, tfiltro, texto):
        textos, cores = filtro.carregar()
        for i in xrange(len(textos)):
            if textos[i].upper() in texto.upper():
                tf1 = '<font color=' +cores[i]+ '>' +texto.replace(' ','&nbsp;')+ '</font>'
                tfiltro.append(tf1)
            
    def atualizaSerial(self, texto):
        self.ui.tserial.inserir(texto)
        f1 = Variaveis(self.PASTA,'filtro1')
        f2 = Variaveis(self.PASTA,'filtro2')
        txt = (self.buffer1+texto).split('\n')
        for i in xrange(len(txt)-1):
            self.atualizaFiltros(f1,self.ui.tfiltro1,txt[i])
            self.atualizaFiltros(f2,self.ui.tfiltro2,txt[i])
        self.buffer1 = txt[-1]

    def configuradialog(self):
        config = Configuracao(Configuracoes(self.tester.ultimoarquivo),self)
        config.setModal(True)
        config.show()

    def timestamp(self):
        merda = Dialog_TStamp(self)
        merda.show()
    
    def sobre(self):
        about = Sobre(self)
        about.show()

    def close_window(self):
        exit()
        
    def conectarserial(self):
        self.ui.tserial.append('Conectando...')
        try:
            self.tester.conectarserial()
            self.ui.tserial.inserir('OK\n')
            self.ui.actionTimestampSerial.setChecked(True)
            self.ui.conexSerial.setIcon(self.iconon)
            self.ui.conexSerial.setToolTip("Desconectar")
        except (Exception), porta:
            QtGui.QMessageBox.critical(self,'Erro!',('Nao foi possivel conectar o serial'))
            self.ui.tserial.append('FALHOU')

    def desconectarserial(self):
        self.ui.tserial.append('\nDesconectando...')
        self.tester.desconectarserial()
        self.ui.conexSerial.setIcon(self.iconoff)
        self.ui.conexSerial.setToolTip("Conectar")
    
    def enviarComandoSSH(self):
        comando = str(self.ui.comandoSSH.text())
        self.ui.comandoSSH.addcommand(comando)
        if self.tester.ssh.conectado:
            self.tester.ssh.enviaComando(comando)
        self.ui.comandoSSH.clear()
        
    def enviarComandoSerial(self):
        comando = str(self.ui.comandoSerial.text())
        self.ui.comandoSerial.addcommand(comando)
        if self.tester.conectadoSerial:
            if comando == '+++' or comando == '@@@':
                self.tester.serial1.write(comando)
            else:
                for c in comando:
                    self.tester.serial1.write(c)
                self.tester.serial1.write('\r')
        self.ui.comandoSerial.clear()

    def telaf1config(self):
        telaVars = Variaveisui(self.PASTA,'filtro1',self)
        telaVars.show()

    def telaf2config(self):
        telaVars = Variaveisui(self.PASTA,'filtro2',self)
        telaVars.show()
# --------------------------- FIM testerui --------------------

from aboutdialog import Ui_Dialog

class Sobre(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

class Configuracao(QtGui.QDialog):
    def __init__(self,configuracoes, parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_config()
        self.ui.setupUi(self)
        self.config = configuracoes
        self.ui.serverssh.insert(self.config.ssh_ip)
        self.ui.portassh.insert(self.config.ssh_porta)
        self.ui.loginssh.insert(self.config.ssh_login)
        self.ui.senhassh.insert(self.config.ssh_senha)
        self.ui.portarvs.insert(self.config.rvs_porta)
        self.ui.protocolorvs.insert(self.config.rvs_protocolo)
        self.ui.comandorvs.insert(self.config.rvs_comando)
        self.ui.velocidade.insert(self.config.ser_speed)
        self.ui.portaserial_2.insert(self.config.ser_porta)
        
        if self.config.use_proxy == '1':
            self.ui.checkBox.setChecked(True)
        else:
            self.ui.radioButton.setEnabled(False)
            self.ui.radioButton_2.setEnabled(False)
            self.ui.radioButton_3.setEnabled(False)
            self.ui.label_9.setEnabled(False)
            self.ui.label_11.setEnabled(False)
            self.ui.lineEdit_2.setEnabled(False)
            self.ui.lineEdit.setEnabled(False)
            self.ui.label_12.setEnabled(False)
            self.ui.lineEdit_3.setEnabled(False)
            self.ui.label_13.setEnabled(False)
            self.ui.lineEdit_4.setEnabled(False)
        if self.config.proxytype == '1':
            self.ui.radioButton.setChecked(True)
        elif self.config.proxytype == '2':
            self.ui.radioButton_2.setChecked(True)
        else:
            self.ui.radioButton_3.setChecked(True)
            
        self.ui.lineEdit.insert(self.config.proxyaddr)
        self.ui.lineEdit_2.insert(self.config.proxylogin)
        self.ui.lineEdit_3.insert(self.config.proxysenha)
        self.ui.lineEdit_4.insert(self.config.proxyport)

        QtCore.QObject.connect(self.ui.portaserial,QtCore.SIGNAL("accepted()"),self.salva)
        QtCore.QObject.connect(self.ui.checkBox,QtCore.SIGNAL("stateChanged(int)"),self.a)

    def a(self,st):
        state = bool(st)
        self.ui.radioButton.setEnabled(state)
        self.ui.radioButton_2.setEnabled(state)
        self.ui.radioButton_3.setEnabled(state)
        self.ui.label_9.setEnabled(state)
        self.ui.label_11.setEnabled(state)
        self.ui.lineEdit_2.setEnabled(state)
        self.ui.label_12.setEnabled(state)
        self.ui.lineEdit_3.setEnabled(state)
        self.ui.label_13.setEnabled(state)
        self.ui.lineEdit_4.setEnabled(state)
        self.ui.lineEdit.setEnabled(state)
        
    def salva(self):
        self.config.ssh_ip = str(self.ui.serverssh.text())
        self.config.ssh_porta = str(self.ui.portassh.text())
        self.config.ssh_login = str(self.ui.loginssh.text())
        self.config.ssh_senha = str(self.ui.senhassh.text())
        self.config.rvs_porta = str(self.ui.portarvs.text())
        self.config.rvs_protocolo = str(self.ui.protocolorvs.text())
        self.config.rvs_comando = str(self.ui.comandorvs.text())
        self.config.ser_porta = str(self.ui.portaserial_2.text())
        self.config.ser_speed = str(self.ui.velocidade.text())
        
        if self.ui.radioButton.isChecked():
            self.config.proxytype = 1
        elif self.ui.radioButton_2.isChecked():
            self.config.proxytype = 2
        else:
            self.config.proxytype = 3
            
        self.config.use_proxy = int(self.ui.checkBox.isChecked())
        self.config.proxyaddr = str(self.ui.lineEdit.text())
        self.config.proxylogin = str(self.ui.lineEdit_2.text())
        self.config.proxysenha = str(self.ui.lineEdit_3.text())
        self.config.proxyport= str(self.ui.lineEdit_4.text())

        self.config.gravar()

#by Varaska
class Dialog_TStamp(QtGui.QDialog):

    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self,parent)
        self.ui = Ui_Dialog_Timestamp()
        self.ui.setupUi(self)
        self.item = None
    
    def calcula(self):
        valor = bin(int(str(self.ui.lineEdit_Valor.text()),16))[2:].zfill(32)
        year = str(int(valor[0:6],2)+1990)
        month = str(int(valor[6:10],2)).zfill(2)
        day =  str(int(valor[10:15],2)).zfill(2)
        hour = str(int(valor[15:20],2)).zfill(2)
        minute = str(int(valor[20:26],2)).zfill(2)
        second = str(int(valor[26:],2)).zfill(2)
        
        self.ui.lineEdit_Data.setText(day+'/'+month+'/'+year)
        self.ui.lineEdit_Hora.setText(hour+':'+minute+':'+second)
        
class configuratorpro(KThread):
    def __init__(self, tester, ip="189.19.92.68", port="9391", apn="wap.vivo.com.br", login="vivo", senha="vivo", device=True):
        self.tester = tester
        self.ip = str(ip)
        self.port = hex(int(str(port)))[2:]
        self.apn = str(apn)
        self.login = str(login)
        self.senha = str(senha)
        self.device = ("12" if (device == True) else "13")
        KThread.__init__(self)

    def run(self):
        self.tester.comandoserial("+++")
        sleep(1)
        for i in xrange(6):
            idx = hex(i*3 + 9)[2:]
            self.cmd("exec "+self.device+" "+idx+" 0 "+self.ip)
            idx = hex(i*3 + 10)[2:]
            self.cmd("exec "+self.device+" "+idx+" "+self.port)
        self.cmd("exec "+self.device+" 1c 0 "+self.apn)
        self.cmd("exec "+self.device+" 1d 0 "+self.login)
        self.cmd("exec "+self.device+" 1e 0 "+self.senha)
        self.cmd("exit")

        
    def cmd(self, str):
        for c in str:
            self.tester.comandoserial(c)
        self.tester.comandoserial('\r')
        sleep(0.5)
        
from autoconfigurator import Ui_autoconfigserial
class AutoConfigurator(QtGui.QDialog):
    def __init__(self, tester, parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_autoconfigserial()
        self.ui.setupUi(self)
        self.tester = tester
        
        
    def accept(self):
        if self.tester.conectadoSerial:
            self.configurando = configuratorpro(self.tester, self.ui.ip.text(), self.ui.porta.text(), self.ui.apn.text(), self.ui.login.text(), self.ui.senha.text(), self.ui.yamaha.isChecked())
            self.configurando.start()
        self.hide()
        

#-----------------------------------------------------
if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    myapp = StartQt4()
    myapp.show()
    myapp.setarapp(app)
    sys.exit(app.exec_())
